package com.sys.tool;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.visitors.HtmlPage;

import java.io.IOException;
import java.net.URI;
import java.util.*;


/**
 * Created by IntelliJ IDEA.
 * User: mabo
 * Date: 2009-10-20
 * Time: 16:31:33
 * To change this template use File | Settings | File Templates.
 */
public class HttpClientTool {


    protected final Log log = LogFactory.getLog(getClass());

    private HttpClient hc;
    private HttpGet hg;
    private HttpPost httpPost;

    private HttpResponse hr;
    private HttpEntity he;


    public HttpClientTool() {
        hc = new DefaultHttpClient();
        hg = new HttpGet();
        httpPost = new HttpPost();
    }


    public void setUrl(String url) {
        try {
            hg = new HttpGet(url);
        } catch (Exception e) {

        }

    }

    public void addHeader(String name, String value) {
        hg.addHeader(name, value);
        httpPost.addHeader(name, value);
    }

    public void close() {
        hc.getConnectionManager().shutdown();
    }

    public void execute() {
        if (hg != null) {
            try {
                hr = hc.execute(hg);
                System.out.println(hr.getStatusLine());
            } catch (IOException e) {
                log.warn("读取页面错误，URL=" + hg.getURI());
                FileTool ft = new FileTool("E:\\sjjy\\bug");
                ft.createFile(new Date().toString().trim().replace(".", ""), "读取页面错误，URL=" + hg.getURI() + "\n\n" + e.toString());
            }
        }
    }


    public String getInnerHTML() {
        return this.getInnerHTML("UTF-8");
    }

    public String getInnerHTML(String encoding) {
        try {
            execute();
            if (hr.getEntity() != null) {
                return EntityUtils.toString(hr.getEntity(), encoding);
            }
        } catch (Exception e) {
            //e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            log.warn("获得HTML代码错误，URL=" + hg.getURI());
        }
        return "";
    }


    public byte[] getByteArray() {
        try {
            execute();
            if (hr.getEntity() != null) {
                return EntityUtils.toByteArray(hr.getEntity());
            }
        } catch (Exception e) {
            //e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            log.warn("获得HTML代码错误，URL=" + hg.getURI());
        }
        return null;
    }


    /**
     * List<NameValuePair> list = new ArrayList<NameValuePair>();
     * list.add(new BasicNameValuePair("edtStudentID", "1112830"));
     * list.add(new BasicNameValuePair("edtPassword", "01260"));
     * list.add(new BasicNameValuePair("__EVENTTARGET", "btnSearch"));
     * list.add(new BasicNameValuePair("__VIEWSTATE", "dDwtMzQ5NDE2NDMwO3Q8O2w8aTwyPjs+O2w8dDw7bDxpPDk+Oz47bDx0PHA8bDx2YWx1ZTs+O2w86KejICDplIE7Pj47Oz47Pj47Pj47PohG/2GfWW4iDo4FkpwpstcnUecB"));
     *
     * @param url
     * @param p
     * @return
     */
    public String post(String url, List p) {
        httpPost.setURI(URI.create(url));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(p, HTTP.UTF_8));
            hr = hc.execute(httpPost);
            return EntityUtils.toString(hr.getEntity(), "gb2312");
        } catch (IOException e) {
//            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            return null;
        }

    }

    public static void main(String[] args) {
//        HttpClientTool hct = new HttpClientTool();
//        hct.setUrl("http://city.qq.com/json.php?mod=search&act=page&callback=showSrchResult&jsontype=str&perpage=12&cd=110000&xb=0&type=city&pg=22");
//        hct.addHeader("Referer", "http://city.qq.com/html/search.htm");


        HttpClientTool hct = new HttpClientTool();
        hct.setUrl("http://www.jiayuan.com/login/dologin.php?pre_url=/usercp&name=mabo%40ccapp.net&password=111222&remem_pass=on&ljg_login=1");
        hct.getInnerHTML();

        hct.setUrl("http://www.jiayuan.com/msg/showmsg.php?msg_id=47351732_1303803193_2_1303834682_ev01&box_type=outbox");

        Parser p = Parser.createParser(hct.getInnerHTML(), "UTF-8");
        HtmlPage page = new HtmlPage(p);
        try {
            p.visitAllNodesWith(page);
        } catch (ParserException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        NodeList nodeBodylist = page.getBody();
        NodeList nodelist;
        Node[] n;

        nodelist = nodeBodylist.extractAllNodesThatMatch(new HasAttributeFilter("onmousedown", "send_jy_pv2('msg_kx_nc');"), true);
        if (nodelist.size() > 0) {
            n = nodelist.toNodeArray();
            System.out.println(((LinkTag) n[0]).getLinkText());//name
            System.out.println(((LinkTag) n[0]).getLink());//url
        }

        nodelist = nodeBodylist.extractAllNodesThatMatch(new HasAttributeFilter("class", "about"), true);
        if (nodelist.size() > 0) {
            n = nodelist.extractAllNodesThatMatch(new TagNameFilter("p"),true).toNodeArray();
            System.out.println(n[0].toPlainTextString());//other
        }


         nodelist = nodeBodylist.extractAllNodesThatMatch(new HasAttributeFilter("onmousedown", "send_jy_pv2('msg_kx_zp');"), true);
        if (nodelist.size() > 0) {
            n = nodelist.extractAllNodesThatMatch(new TagNameFilter("img"),true).toNodeArray();
            System.out.println(((ImageTag) n[0]).getImageURL());
        }


    }

}
